// pages/detail/detail.js
const util = require('../../utils/util.js');
var mta = require('../../utils/mta_analysis.js');
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prizeDialogDisplay: 'none',
    shareDialogDisplay: 'none',
    prizeTip: { msg: '暂未中奖', image:'/resources/card.png'},
    userInfo:{},
    cardUser: {},
    cardActivity:{
      title: '正在加载标题',
      banner:'',
      intro:'正在加载活动介绍',
      rule:'正在加载活动规则',
      content:'',
      prizeCount:0,
      prizeLeft:0,
      id:0
    },
    cards:[
    ],
    winners: [
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    mta.Page.init();
    this.initShare(options);
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let userId = this.data.cardUser.id;
    let userNick = this.data.cardUser.nick;
    let activityId = this.data.cardActivity.id;
    let shareImage = this.data.cardActivity.shareImage || '/resources/shareImage.jpg';
    mta.Event.stat("clickshare", {}); //点击分享
    if (res.from === 'button' || res[0].from === 'button') {
      // 来自页面内转发按钮
      mta.Event.stat('xiangqingyefenx', { 'clicksharetofriend': 'true' });
      return {
        title: userNick + '正在集福，你可以给TA赐一张福',
        path: '/pages/assistance/assistance?id=' + activityId + '&userId=' + userId,
        imageUrl: shareImage,
        success: function (res) {
          mta.Event.stat('xiangqingyefenx', { 'clicksharetofriendsuccess': 'true' });
          if (res && res.shareTickets && res.shareTickets.length > 0){
            mta.Event.stat('clickshare', { 'clickshare2group': 'true' });//分享到群聊
          }else{
            mta.Event.stat('clickshare', { 'clickshare2friend': 'true' });//分享独聊
          }
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
    return {
      title: userNick + '分享给你一个福袋，快来看看是什么',
      path: '/pages/detail/detail?id=' + activityId + '&userId=' + userId,
      imageUrl: shareImage,
      success: function (res) {
        if (res && res.shareTickets && res.shareTickets.length > 0) {
          mta.Event.stat('clickshare', { 'clickshare2group': 'true' });//分享到群聊
        } else {
          mta.Event.stat('clickshare', { 'clickshare2friend': 'true' });//分享独聊
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  initShare: function(options){
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        console.log('shareMenu share success')
        console.log(res);
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  initData: function (options){
    this.getActivityDetail(options,{
      success: function (options){
        this.getUserDetail(options);//这个一定要放在成功之后的回调里，因为cards的count需要先初始化card数组
      }
    });
    this.getWinnerList(options);
  },

  getActivityDetail: function (options,callback){
    var activityId = options.id || 0;
    var that = this;

    wx.showLoading({
      title: '数据加载中',
    })

    wx.request({
      url: app.host + '/card/detail',
      data: { id: activityId },
      method: 'GET',
      header: {
        "Content-Type": "applciation/json"
      },
      success: function (res) {
        if (res && res.data && res.data.code > 0) {
          wx.hideLoading();
          var cardActivity = res.data.data.activity;
          cardActivity.startTime = util.formatTime(new Date(cardActivity.startTime));
          cardActivity.endTime = util.formatTime(new Date(cardActivity.endTime));
          that.setData({ cardActivity: cardActivity});
          that.setData({ cards: res.data.data.cards});

          WxParse.wxParse('rule', 'html', cardActivity.rule, that, 5);
          WxParse.wxParse('intro', 'html', cardActivity.intro, that, 5);

          callback && callback.success && callback.success.call(that, options);

        } else {
          wx.showToast({
            title: '活动信息加载失败,请售后再试',
          })

        }
      },
      fail:function(){
        wx.hideLoading();
      }
    })
  },

  getUserDetail: function (options){

    let that = this;
    let activityId = options.id || 0;
    let openid = app.globalData.openid || wx.getStorageSync('openid');

    if (activityId && openid){

      wx.getUserInfo({
        success: function (res) {
          that.setData({ userInfo: res.userInfo });
          wx.setNavigationBarTitle({
            title: '集福大狂欢，瓜分几个亿,' + res.userInfo.nickName + '给你分享了几个亿'
          });
        }
      });

      wx.request({
        url: app.host + '/card/getUserInfoByActivityIdAndOpenid',
        data: { activityId: activityId, openid: openid },
        method: 'GET',
        header: {
          "Content-Type": "applciation/json"
        },
        success: function (res) {

          if(res && res.data ){

            if(res.data.code > 0){
              let cardUser = res.data.data.user;
              that.setData({ cardUser: res.data.data.user });
              that.cardUser = res.data.data.user;
              that.initUserCardCount(res.data.data.user);
            } else if (res.data.code == -404){
              that.registerCardUser(activityId);
            }

          }
        }
      })
    }
    
  },

  registerCardUser: function (activityId){
    let that = this;
    wx.getUserInfo({
      success: function (res) {
        let data = res.userInfo;
        data.activityId = activityId;
        data.openid = app.globalData.openid;

        wx.request({
          url: app.host + 'card/register',
          data: data,
          method: 'POST',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: function (res) {
            that.setData({ cardUser: res.data.data.user });
            that.initUserCardCount(res.data.data.user);
          }
        })

      }
    });
  },

  getWinnerList: function(options){
    var activityId = options.id || 1;
    var that = this;

    wx.request({
      url: app.host + '/card/winners',
      data: { id: activityId },
      method: 'GET',
      header: {
        "Content-Type": "applciation/json"
      },
      success: function (res) {
        if (res && res.data && res.data.code > 0) {
          var winners = res.data.data.winners;
          that.setData({ winners: winners });
        }
      }
    })
  },

  initUserCardCount: function(cardUser){
    console.log(cardUser);
    if(cardUser){
      let cards = this.data.cards;
      if (cardUser.card1Count > 0) { cards[0].count = cardUser.card1Count;}
      if (cardUser.card2Count > 0) { cards[1].count = cardUser.card2Count; }
      if (cardUser.card3Count > 0) { cards[2].count = cardUser.card3Count; }
      if (cardUser.card4Count > 0) { cards[3].count = cardUser.card4Count; }
      if (cardUser.card5Count > 0) { cards[4].count = cardUser.card5Count; }
      if (cardUser.card6Count > 0) { cards[5].count = cardUser.card6Count; }
      if (cardUser.card7Count > 0) { cards[6].count = cardUser.card7Count; }
      if (cardUser.card8Count > 0) { cards[7].count = cardUser.card8Count; }
      if (cardUser.card9Count > 0) { cards[8].count = cardUser.card9Count; }
      if (cardUser.card10Count > 0) { cards[9].count = cardUser.card10Count; }

      this.setData({cards: cards});

      console.log(cards);

    }
  },

  bindCardCollecting: function (options){
    console.log("抽取福袋");
    mta.Event.stat("clickcollecting", {});
    let that = this;
    if (that.data.cardUser.chance <= 0){
      wx.showModal({
        title: '抽奖提示',
        content: '您已经没有抽奖次数啦，可以邀请好友助力增加抽奖次数',
        showCancel: false
      })
    }else{
      //进入抽奖环节

      let data = {};
      data.openid = app.globalData.openid;
      data.activityId = that.data.cardUser.activityId;

      wx.request({
        url: app.host + '/card/collecting',
        data: data,
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          if (res && res.data && res.data.code > 0) {
            let msg = res.data.msg;
            let image = res.data.data.t.image || '/resources/card.png';
            that.showPrizeDialog(msg, image);
            that.getUserDetail({ id: that.data.cardUser.activityId});
          }else{
            let message = res.data.msg || '抱歉，未抽中任何福袋';
            wx.showModal({
              title: '集福提示',
              content: message,
              showCancel:false
            })
          }
        }
      })

    }

  },
  bindShareButton: function(){
    mta.Event.stat('xiangqingyefenx', { 'clickshare': 'true' });
    this.setData({ shareDialogDisplay: 'fixed' });
  },
  bindShareToFriend: function(){
    this.setData({ shareDialogDisplay: 'none' });
  },
  bindShareToTimeline: function () {
    let that = this;
    let data = this.data.cardUser;

    wx.showLoading({
      title: '正在生成分享图',
    })

    wx.request({
      url: app.host + '/card/getShareImage',
      data: data,
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res && res.data && res.data.code > 0) {
          wx.hideLoading();
          wx.showModal({
            content: '分享图片已保存至本地相册，请直接在朋友圈选择图片分享',
            showCancel: false
          });
          that.saveNetworkImage(res.data.data.imageUrl);
        }
      }
    })

    this.setData({ shareDialogDisplay: 'none' });
  },
  showPrizeDialog: function(msg, image){
    this.setData({ prizeDialogDisplay: 'fixed',
                    prizeTip:{msg:msg,image:image}
                    });
  },
  bindClosePrizeDialog: function(){
    this.setData({prizeDialogDisplay: 'none'});
  },
  bindViewMore: function(){
    mta.Event.stat("clickviewmore", {});
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  bindContactMe: function(){
    mta.Event.stat("clickiwanttopublishactivity", {});
    wx.navigateToMiniProgram({
      appId: 'wxbf6745c33954c6d0',
      path: 'pages/index/index',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'trial',
      success(res) {
        // 打开成功
      }
    })
  },
  bindClickDraw: function(){

    let that = this;
    let cardUser = this.data.cardUser;
    let data = { cardUserId: cardUser.id};

    wx.request({
      url: app.host + '/card/draw',
      data: data,
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res && res.data && res.data.code > 0) {
          wx.hideLoading();
          cardUser.winner = true;
          that.setData({ cardUser: cardUser});
        }else{
          let message = res.data.msg || '开奖失败，请稍候再试';
          wx.showToast({
            title: message,
          })
        }
      }
    })

  },
  bindClickViewMyPrize: function(){
    wx.switchTab({
      url: '/pages/my/my',
    })
  },
  bindGetMoreChance: function(){
    mta.Event.stat("clickgetmorechance", {});
  },
  bindIWantToPublishActivity: function(){
    mta.Event.stat("clickiwanttopublishactivity", {});
  },
  saveNetworkImage: function(imageUrl){
    wx.downloadFile({
      url: imageUrl,
      success: function (res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            console.log(res)
          },
          fail: function (res) {
            console.log(res)
            console.log('fail')
          }
        })
      },
      fail: function () {
        console.log('fail')
      }
    });
  }
})